package com.example.nowcodercommunity.controller;

import com.example.nowcodercommunity.entity.DiscussPost;
import com.example.nowcodercommunity.entity.Page;
import com.example.nowcodercommunity.entity.User;
import com.example.nowcodercommunity.service.CommunityConstant;
import com.example.nowcodercommunity.service.DiscussPostService;
import com.example.nowcodercommunity.service.LikeService;
import com.example.nowcodercommunity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController {

    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    /**
     * 简单的主页
     * @param model
     * @param page
     * @return
     */
    @RequestMapping(path = "/index",method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page){
        // 先设置Page显示情况，这里没设置上限，因为默认为10
        page.setTotalRows(discussPostService.findDiscussPostRows(0));
        page.setSearchPath("/index");

//        System.out.println(page.getTotalPages());
//        System.out.println(page.getFrom());
//        System.out.println(page.getLimit());
        List<DiscussPost> discussPostsWithinUser = discussPostService.findDiscussPostsWithinUser(0, page.getFrom(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();

        if(discussPostsWithinUser != null){
            for(DiscussPost post:discussPostsWithinUser){
                Map<String, Object> map = new HashMap<>();
//                System.out.println(post.toString());
                map.put("post",post);
                User user = userService.findUserById(post.getUserId());
//                System.out.println(user.toString());
                map.put("user", user);

                long entityLikeCount = likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, post.getId());
                map.put("likeCount",entityLikeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }

    /**
     * 错误页处理
     * @return
     */
    @RequestMapping(path = "/error",method = RequestMethod.GET)
    public String errorPage(){
        return "/error/500";
    }
}
